import { FormInstance, Rule } from 'ant-design-vue/lib/form';
import { Form, message } from "ant-design-vue";
import { ref } from 'vue'
import apis from '@/apis/index';

export function useCaptcha (_formRef: FormInstance, _email: string)  {
  //- 定义-验证码响应式数据
  const captchaStrRef = ref<string>("");
  const formRef = ref<FormInstance>(_formRef);
  const emailStrRef = ref<string>(_email);
  const isSendedCaptchaRef = ref<boolean>(false);
  const isDisabledCaptchaRef = ref<boolean>(false);
  const currentCountNumRef = ref<number>(60);

  //- 方法-验证验证码
  const validateCaptcha = async (_rule: Rule, _value: string) => {
    // 1.判断是否为空值
    if (_value === "") {
      return Promise.reject("验证码不能为空");
    }
    // 2.判断密码长度是否不等于6
    if (_value.length !== 6) {
      return Promise.reject("验证码长度不正确");
    }
    return Promise.resolve();
  };

  //- 验证码校验规则
  const captchaRulesArr: Array<Object> = [
    { required: true, validator: validateCaptcha }
  ];

  // 开始倒计时
  const startCountDown = () => {
    const timer = setInterval(() => {
      // 判断是否倒计时结束
      if (currentCountNumRef.value === 0) {
        clearInterval(timer);
        // 1.修改发送状态
        isSendedCaptchaRef.value = false;
        // 2.修改禁用状态
        isSendedCaptchaRef.value = false;
        // 3.当前时间重新回到最大时间
        currentCountNumRef.value = 60;
        return;
      }
      // 倒计时
      currentCountNumRef.value--;
    }, 1000);
  };

  //- 发送验证码
  const handleSendCaptcha = async () => {
    // 发送验证码
    try {
      // 1.判断邮箱是否存在数据库中
      const isExist = await apis.user.isExists_API({ email: emailStrRef.value });
      if (!isExist) {
        // 邮箱不存在
        message.error("邮箱账号无效");
        // 重置表单
        formRef.value.resetFields();
        return;
      }
      console.log(isExist, "邮箱是否存在");
      // 2.有效则发送验证码，无效则提示邮箱无效
      // 2.1修改已经发送的状态
      isSendedCaptchaRef.value = true;
      // 2.2按钮设为禁用状态
      isDisabledCaptchaRef.value = true;
      // 2.3开始倒计时
      startCountDown();
      const resData = await apis.user.getEmailCode_API(emailStrRef.value);
      if (resData) {
        sessionStorage.clear();
        sessionStorage.setItem("captcha", resData.code);
        message.success("验证码发送成功，请注意查收");
        console.log(resData);
      }
    } catch (error) {
      console.log(error, "error");
    }
  };

  //- 返回暴露数据
  return {
    captchaStrRef,
    captchaRulesArr,
    currentCountNumRef,
    isDisabledCaptchaRef,
    isSendedCaptchaRef,
    handleSendCaptcha,
  }
}